package org.budo.dubbo.protocol.http.aop.permission.user;

import java.lang.reflect.Method;

import org.budo.dubbo.protocol.http.authentication.AuthenticationCheck;
import org.budo.dubbo.protocol.http.authentication.AuthenticationCheckMethodInterceptor;
import org.budo.dubbo.protocol.http.util.BudoReflectionUtil;
import org.budo.support.lang.util.BooleanUtil;
import org.budo.support.mvcs.Mvcs;
import org.budo.support.spring.aop.util.AopUtil;
import org.budo.support.spring.context.aware.BudoApplicationContextAware;

import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Slf4j
public class UserPermissionCheckUtil {
    public static Boolean requireUserPermissionCheck(Method method) {
        if (AopUtil.aopShouldSkip(method)) {
            return false;
        }

        UserPermissionCheck annotation = BudoReflectionUtil.getMethodAnnotationCached(method, UserPermissionCheck.class);
        if (null != annotation) {
            return annotation.check();
        }

        AuthenticationCheck authenticationCheck = BudoReflectionUtil.getMethodAnnotationCached(method, AuthenticationCheck.class);
        if (null != authenticationCheck && !(authenticationCheck.requires() && authenticationCheck.value())) {
            return false;
        }

        Boolean requireAuthenticationCheck = (Boolean) Mvcs.getRequestAttribute(AuthenticationCheckMethodInterceptor.REQUIRE_AUTHENTICATION_CHECK);
        if (BooleanUtil.isFalse(requireAuthenticationCheck)) {
            return false;
        }

        return defaultUserPermissionCheck();
    }

    private static Boolean defaultUserPermissionCheck() {
        if (null == BudoApplicationContextAware.getInstance()) {
            log.debug("#69 defaultAuthenticationCheck_aop return false, not inited");
            return false; // 启动阶段不执行 aopInterceptor
        }

        UserPermissionCheckMethodInterceptor methodInterceptor = BudoApplicationContextAware.getBeanCached_2(UserPermissionCheckMethodInterceptor.class);
        if (null != methodInterceptor) {
            return methodInterceptor.getDefaultUserPermissionCheck();
        }

        return false;
    }
}